<!--  -->
<template>
  <div class="">
    <a-card :bordered="false" class="search-wrapper">
      <div class="search-box">
        <a-tabs v-model="tabActive" :style="{ height: '50px' }" @tabClick="typeClick">
          <a-tab-pane v-for="(item, index) in tabList" :key="index" :tab="item.name"></a-tab-pane>
        </a-tabs>
      </div>
      <div class="search-form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input v-model="filter.name" placeholder="项目名称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <financial-select v-model="filter.productCode" placeholder="金融产品" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <brand-select v-model="filter.brandCode" placeholder="标的公司" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <CapitalSelect v-model="filter.capitalCode" placeholder="资方" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <store-select v-model="filter.storeCode" placeholder="投资店铺" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-range-picker
                  @change="onChange"
                  v-model="filter._dateRange"
                  :placeholder="['履约开始时间', '履约结束时间']"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input v-model="filter.createBy" placeholder="创建人" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24" v-if="tabActive == 0">
              <a-form-item>
                <DateTimeRange
                  v-model="filter._dateRange1"
                  :startDate.sync="filter.beginTime"
                  :endDate.sync="filter.endTime"
                  :placeholder="['创建开始时间', '创建结束时间']"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24" v-else>
              <a-form-item>
                <DateTimeRange
                  v-model="filter._dateRange1"
                  :startDate.sync="filter.auditBeginTime"
                  :endDate.sync="filter.auditEndTime"
                  :placeholder="['审核开始时间', '审核结束时间']"
                />
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handle">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (filter = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card class="table-wrapper">
      <div class="box">
        <div class="box-act" v-if="tabActive == 0">
          <a-button size="small" @click="batchHandler('pass')"> 批量审核通过 </a-button>
          <a-button size="small" @click="batchHandler('reject')"> 批量审核驳回 </a-button>
        </div>
      </div>
      <a-table
        :loading="tableLoading"
        bordered
        :columns="[...columns, ...tabList[tabActive].columns]"
        :pagination="pagination"
        :data-source="tableData || []"
        @change="(e) => handle(e)"
        :scroll="{ y: tableHeight, x: 'max-content' }"
        :row-selection="
          tabActive == 0 ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange } : null
        "
      >
        <template slot="name" slot-scope="text, record">
          <div class="text">{{ text }}</div>
          （{{ record.code }}）
        </template>
        <template slot="productName" slot-scope="text, record">
          <div class="text">{{ text }}</div>
          （{{ record.productCode }}）
        </template>
        <template slot="brandName" slot-scope="text, record">
          <div class="text">{{ text }}</div>
          （{{ record.brandCode }}）
        </template>
        <span slot="storeCode" slot-scope="text, record">
          <div class="text">{{ text }}</div>
          {{ (record.storeCode ? '（' + record.storeCode + '）' : '--') }}
        </span>
        <template slot="capitalName" slot-scope="text, record">
          <div class="text">{{ text }}</div>
          （{{ record.capitalCode }}）
        </template>
        <span slot="performanceStartTime" slot-scope="text, record">
          {{ text }}~{{ record.performanceEndTime }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="tabActive == 0">
            <a-button type="link" @click="auditHandler(record, 'pass')">审核通过</a-button>
            <a-button type="link" @click="auditHandler(record, 'reject')">审核驳回</a-button>
          </template>
          <a-button type="link" @click="handlerProgress(record)">审批进度</a-button>
        </span>
      </a-table>
    </a-card>
    <project-progress ref="project-progress"></project-progress>
    <project-form ref="project-form" @on-submit="handle"></project-form>
  </div>
</template>

<script>
import { getProjectList, setProjectAuditPass } from '@/api/invest'
import { DateTimeRange } from '@/components'
import ProjectForm from './module/project-form'
import ProjectProgress from './module/project-progress'
import CapitalSelect from '@/myComponents/capital-select'
import BrandSelect from '@/myComponents/brand-select.vue'
import FinancialSelect from '@/myComponents/financial-select'
import StoreSelect from '@/myComponents/store-select'
import moment from 'moment'
import { digitSymbolFormat } from '@/utils/index'
// const startTime = moment().subtract(3, 'days').format('YYYY-MM-DD 00:00:00')
// const endTime = moment().format('YYYY-MM-DD 23:59:59')
export default {
  data() {
    return {
      tableLoading: false,
      tabActive: 0,
      subBranch: [],
      filter: {
        pageSize: 10,
        pageNum: 1,
        beginTime: '',
        endTime: '',
        name: '',
        productCode: undefined,
        capitalCode: undefined,
        createBy: '',
        _dateRange: [],
        _dateRange1: [],
        status: '0',
        auditEndTime: '',
        auditBeginTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        'show-size-changer': true,
        total: 0
      },
      columns: [
        { title: '项目', dataIndex: 'name', scopedSlots: { customRender: 'name' } },
        {
          title: '金融产品',
          dataIndex: 'productName',
          scopedSlots: { customRender: 'productName' }
        },
        { title: '标的公司', dataIndex: 'brandName', scopedSlots: { customRender: 'brandName' } },
        { title: '投资店铺', dataIndex: 'storeName', scopedSlots: { customRender: 'storeCode' } },
        {
          title: '融资金额(元)',
          dataIndex: 'financingAmount',
          customRender: (text) => digitSymbolFormat(text)
        },
        { title: '资方', dataIndex: 'capitalName', scopedSlots: { customRender: 'capitalName' } },
        {
          title: '出金金额(元)',
          dataIndex: 'investAmount',
          customRender: (text) => digitSymbolFormat(text)
        },
        {
          title: '履约时间',
          dataIndex: 'performanceStartTime',
          scopedSlots: { customRender: 'performanceStartTime' }
        },
        { title: '创建人', dataIndex: 'createBy' }
        // { title: '创建时间', dataIndex: 'createTime' },
        // {
        //   title: '操作',
        //   key: 'action',
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      tabList: [
        {
          name: '待审核',
          value: 0,
          columns: [
            { title: '创建时间', dataIndex: 'createTime' },
            {
              title: '操作',
              key: 'action',
              scopedSlots: { customRender: 'action' }
            }
          ]
        },
        {
          name: '审核通过',
          value: 1,
          columns: [
            { title: '审核时间', dataIndex: 'auditTime' },
            {
              title: '操作',
              key: 'action',
              scopedSlots: { customRender: 'action' }
            }
          ]
        },
        {
          name: '审核驳回',
          value: 2,
          columns: [
            { title: '审核时间', dataIndex: 'auditTime' },
            { title: '驳回原因', dataIndex: 'remark' },
            {
              title: '操作',
              key: 'action',
              scopedSlots: { customRender: 'action' }
            }
          ]
        }
      ],
      selectedRowKeys: [],
      selectedRows: [],
      remark: ''
    }
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    tableHeight() {
      return document.body.clientHeight - this.tabbarHeight
    }
  },
  components: {
    DateTimeRange,
    ProjectForm,
    ProjectProgress,
    CapitalSelect,
    BrandSelect,
    FinancialSelect,
    StoreSelect
  },
  mounted() {
    const queryRoute = this.$route.query
    if (queryRoute.viewState) {
      const find = this.tabList.findIndex((v) => v.value == queryRoute.viewState)
      this.filter.status = queryRoute.viewState
      this.tabActive = find
    }
    this.handle()
  },
  activated() {
    const queryRoute = this.$route.query
    if (queryRoute.viewState) {
      const find = this.tabList.findIndex((v) => v.value == queryRoute.viewState)
      this.filter.status = queryRoute.viewState
      this.tabActive = find
    }
    this.handle()
  },
  methods: {
    batchHandler(status) {
      if (this.selectedRowKeys.length) {
        const ids = this.selectedRows.map((v) => v.id)
        this.auditHandler({ ids }, status)
      } else {
        this.$notification['error']({
          message: '错误提示',
          description: status == 'pass' ? '请选择批量审核通过数据' : '请选择批量审核驳回数据'
        })
      }
    },
    auditHandler(record, status) {
      const vm = this
      let remark = ''
      this.$confirm({
        title: status == 'pass' ? '审核通过' : '审核驳回',
        width: status == 'pass' ? 416 : 540,
        content: (
          <div>
            {status == 'reject' ? (
              <div>
                <p>确认审核驳回，请填写驳回原因：</p>
                <a-textarea
                  placeholder="请输入"
                  allow-clear
                  auto-size={{ minRows: 3, maxRows: 8 }}
                  onChange={(e) => (remark = e.target.value)}
                ></a-textarea>
              </div>
            ) : (
              <p>确认投资项目审核通过？</p>
            )}
          </div>
        ),
        class: 'confirm-box',
        onOk() {
          return new Promise((resolve, reject) => {
            if (status == 'reject' && !remark) {
              vm.$message['error']('请填写驳回原因')
              return reject(new Error('请填写驳回原因'))
            } else {
              setProjectAuditPass({ idList: record.id ? [record.id] : record.ids, remark }, status)
                .then((resp) => {
                  vm.$notification['success']({
                    message: '成功提示',
                    description: `${status == 'pass' ? '审核通过' : '审核驳回'}成功`
                  })
                  vm.selectedRowKeys = []
                  vm.selectedRows = []
                  vm.handle()
                  resolve()
                })
                .catch(() => {
                  return reject(new Error(''))
                })
            }
          })
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onChange(val) {
      let [performanceBeginTime, performanceEndTime] = val
      this.filter.performanceBeginTime =
        performanceBeginTime && moment(performanceBeginTime).format('YYYY-MM-DD')
      this.filter.performanceEndTime =
        performanceEndTime && moment(performanceEndTime).format('YYYY-MM-DD')
    },
    typeClick(index) {
      if (this.tabActive != index) {
        this.filter.status = this.tabList[index].value
        this.tabActive = index
        this.handle()
      }
    },
    addHandler() {
      this.$refs['project-form'].open()
    },
    editHandler(record) {
      this.$refs['project-form'].open(record)
    },
    handlerProgress(record) {
      this.$refs['project-progress'].open(record)
    },
    handle(v) {
      if (v && v.current) {
        if (this.filter.pageSize == v.pageSize) {
          this.pagination.current = v.current
          this.filter.pageNum = v.current
        } else {
          this.filter.pageSize = v.pageSize
          this.filter.pageNum = 1
          this.pagination.current = 1
        }
      } else {
        this.filter.pageNum = 1
        this.filter.pageSize = 10
        this.pagination.current = 1
      }
      this.tableLoading = true
      getProjectList(this.filter)
        .then((res) => {
          this.tableLoading = false
          this.tableData = res.rows
          this.pagination.total = res.total || 0
        })
        .catch(() => {
          this.tableLoading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.box-act {
  display: flex;
}
.search-box {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  min-height: 47px;
  margin-bottom: 19px;
  .type-list {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    .type-item {
      height: 45px;
      line-height: 45px;
      border-bottom: 2px solid #fff;
      padding: 0 20px;
      font-size: 14px;
      cursor: pointer;
    }
    .type-item.active {
      border-bottom: 2px solid #4393f2;
      font-size: 16px;
      font-weight: 500;
      color: #4393f2;
    }
  }
}
.box-total-item {
  font-size: 12px;
}
</style>
